package com.zhuss.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class FileUtil {
	
	private static final Long 一兆 = 50 * 1024 * 1024l;
	
	private static Long average = 0l;
	
	public static void main(String[] args) throws IOException {
		splitFile("D:\\code\\05\\dzcx\\dzcx-srv\\target\\", "dzcx-srv-0.0.1-SNAPSHOT", ".jar", 1);
		together();
	}
	
	/**
    *
    * @param filePath      文件路径（不包括格式后缀）
    * @param fileFormat    文件后缀格式（如：.txt）
    * @param fileOverSize  文件超过多大才分割（单位：M）
    * @throws IOException
    */
   public static void splitFile(String filePath, String fileName, String fileType, Integer fileOverSize) throws IOException {
       FileInputStream fis = new FileInputStream(filePath + fileName + fileType);
       FileChannel inputChannel = fis.getChannel();
       final long fileSize = inputChannel.size();
       Long fileCount = 1l;
       if (fileSize < fileOverSize * 一兆) {
    	   fileCount = 1l;
       }
       fileCount = fileSize % (fileOverSize * 一兆) == 0 ? fileSize / (fileOverSize * 一兆) : fileSize / (fileOverSize * 一兆) + 1;
//       fileCount = fileSize / (fileOverSize * 一兆);
       average = fileSize / fileCount;//平均值
       long bufferSize = 200; //缓存块大小，自行调整
       ByteBuffer byteBuffer = ByteBuffer.allocate(Integer.valueOf(bufferSize + "")); // 申请一个缓存区
       long startPosition = 0; //子文件开始位置
       long endPosition = 0;
       for (int i = 0; i < fileCount; i++) {
           if (i + 1 != fileCount) {
               int read = inputChannel.read(byteBuffer, endPosition);// 读取数据
               readW:
               while (read != -1) {
                   byteBuffer.flip();//切换读模式
//                    byte[] array = byteBuffer.array();
//                   for (int j = 0; j < array.length; j++) {
//                       byte b = array[j];
//                        if (b == 10 || b == 13) { //判断\n\r
//                            endPosition += j;
//                            break readW;
//                        }
//                   }
                   byteBuffer.clear(); //重置缓存块指针
                   if (endPosition + bufferSize < average * (i + 1)) {
                	   endPosition += bufferSize;
                	   read = inputChannel.read(byteBuffer, endPosition);
                   } else {
                	   endPosition = average * (i + 1);
                	   ByteBuffer byteBuffer2 = ByteBuffer.allocate(Integer.valueOf(average * (i + 1)- endPosition + ""));
                	   read = inputChannel.read(byteBuffer2, endPosition);
                	   break readW;
                   }
               }
           } else {
               endPosition = fileSize; //最后一个文件直接指向文件末尾
           }
           
           String outPath = filePath + "jar\\";
           File folder = new File(outPath);
           if (!folder.exists()) {
        	   folder.mkdir();
           }
           int m = i+1;
           while(new File(outPath + fileName + m + fileType).exists()){
               m++;
           }
           FileOutputStream fos = new FileOutputStream(outPath + fileName + m + fileType);
           FileChannel outputChannel = fos.getChannel();
           inputChannel.transferTo(startPosition, endPosition - startPosition, outputChannel);//通道传输文件数据
           outputChannel.close();
           fos.close();
           startPosition = endPosition;
           endPosition += average;
       }
       inputChannel.close();
       fis.close();
   }
   
   /**
   *
   * @param filePath      文件路径（不包括格式后缀）
   * @param fileFormat    文件后缀格式（如：.txt）
   * @param fileOverSize  文件超过多大才分割（单位：M）
   * @throws IOException
   */
   @Deprecated
  public static void splitFile2(String filePath, String fileName, String fileType, Integer fileOverSize) throws IOException {
      FileInputStream fis = new FileInputStream(filePath + fileName + fileType);
      FileChannel inputChannel = fis.getChannel();
      final long fileSize = inputChannel.size();
      Long fileCount = 1l;
      if (fileSize < fileOverSize * 一兆) {
   	   fileCount = 1l;
      }
      fileCount = fileSize % (fileOverSize * 一兆) == 0 ? fileSize / (fileOverSize * 一兆) : fileSize / (fileOverSize * 一兆) + 1;
//      fileCount = fileSize / (fileOverSize * 一兆);
      average = fileSize / fileCount;//平均值
      long bufferSize = 200; //缓存块大小，自行调整
      ByteBuffer byteBuffer = ByteBuffer.allocate(Integer.valueOf(bufferSize + "")); // 申请一个缓存区
      long startPosition = 0; //子文件开始位置
      long endPosition = 0;
      // long endPosition = average < bufferSize ? 0 : average - bufferSize;//子文件结束位置
       endPosition = average;
      for (int i = 0; i < fileCount; i++) {
//          if (i + 1 != fileCount) {
              int read = inputChannel.read(byteBuffer, endPosition);// 读取数据
              readW:
              while (read != -1) {
                  byteBuffer.flip();//切换读模式
                   byte[] array = byteBuffer.array();
                  for (int j = 0; j < array.length; j++) {
                      byte b = array[j];
                       if (b == 10 || b == 13) { //判断\n\r
                           endPosition += j;
                           break readW;
                       }
                  }
                   endPosition += bufferSize;
                  byteBuffer.clear(); //重置缓存块指针
                  read = inputChannel.read(byteBuffer, endPosition);
              }
//          }else{
//              endPosition = fileSize; //最后一个文件直接指向文件末尾
//          }

          String outPath = filePath + "jar\\";
          File folder = new File(outPath);
          if (!folder.exists()) {
       	   folder.mkdir();
          }
          int m = i+1;
          while(new File(outPath + fileName + m + fileType).exists()){
              m++;
          }
          FileOutputStream fos = new FileOutputStream(outPath + fileName + m + fileType);
          FileChannel outputChannel = fos.getChannel();
          inputChannel.transferTo(startPosition, endPosition - startPosition, outputChannel);//通道传输文件数据
          outputChannel.close();
          fos.close();
          startPosition = endPosition + 1;
          endPosition += average;
      }
      inputChannel.close();
      fis.close();
  }
   
   
   public static void together2() throws IOException {
	   //定义输出目录
       String fileOut="D:\\code\\05\\dzcx\\dzcx-srv\\target\\dzcx-srv.jar";
       BufferedWriter bw=new BufferedWriter(new FileWriter(fileOut));

       //读取目录下的每个文件或者文件夹，并读取文件的内容写到目标文字中去
       File[] list = new File("D:\\code\\05\\dzcx\\dzcx-srv\\target\\jar\\").listFiles();
       int fileCount = 0;
       int folderConut= 0;
       for (File file : list) {
           if (file.isFile()) {
               fileCount ++;
               BufferedReader br = new BufferedReader(new FileReader(file));
               String line;
               while ((line=br.readLine()) != null) {
                   bw.write(line);
                   bw.newLine();
               }
               br.close();
           } else {
               folderConut++;
           }
       }
       bw.close();
       System.out.println("输入目录下文件个数为" + fileCount);
       System.out.println("输入目录下文件夹个数为" + folderConut);
   }
   
   
   public static void together() throws IOException {
	 //定义输出目录
     String fileOut = "D:\\code\\05\\dzcx\\dzcx-srv\\target\\dzcx-srv.jar";
     FileOutputStream fos = new FileOutputStream(fileOut);

     //读取目录下的每个文件或者文件夹，并读取文件的内容写到目标文字中去
       File[] list = new File("D:\\code\\05\\dzcx\\dzcx-srv\\target\\jar\\").listFiles();
       int fileCount = 0;
       int folderConut= 0;
       Long bufferSize = average; //缓存块大小，自行调整
       ByteBuffer byteBuffer = ByteBuffer.allocate(bufferSize.intValue()); // 申请一个缓存区
       List<byte[]> result = new ArrayList<>();
       for(File file : list) {
    	   if(file.isFile()) {
    		   fileCount++; 
    		   String path = file.getAbsolutePath();
    		   FileInputStream fis = new FileInputStream(path);
    		   FileChannel inputChannel = fis.getChannel();
    		   inputChannel.read(byteBuffer);// 读取数据
    		   byte[] byteList = byteBuffer.array();
    		   result.add(byteList);
    		   inputChannel.close();
    		   fis.close();
           }else {
               folderConut++;
           }
       }
       for (byte[] item : result) {
    	   fos.write(item);
       }
       fos.close();
       FileInputStream f = new FileInputStream(fileOut);
       byte[] total = new byte[average.intValue()];
       byte[] total3 = new byte[average.intValue() * 2];
       f.read(total);
       f.read(total3);
       System.out.println(total3.length);
       byte[] total2 = new byte[average.intValue()];
       System.arraycopy(total3, total3.length/2, total2, 0, total2.length);
       System.out.println("");
       System.out.print("total---");
       int j = 0;
       for (int i = 0; i < total.length; i ++) {
    	   //System.out.print(total[i]);
    	   //System.out.print(",");
       }
       System.out.println("输入目录下文件个数为"+fileCount);
       System.out.println("输入目录下文件夹个数为"+folderConut);
       
       String fileOut1 = "D:\\code\\05\\dzcx\\dzcx-srv\\target\\jar\\dzcx-srv-0.0.1-SNAPSHOT1.jar";
       FileInputStream f1 = new FileInputStream(fileOut1);
       byte[] b1 = new byte[average.intValue()];
       f1.read(b1);
       System.out.println("");
       System.out.print("b1---");
       for (int i = 0; i < b1.length; i ++) {
    	   //System.out.print(b1[i]);
    	   //System.out.print(",");
       }
       
       String fileOut2 = "D:\\code\\05\\dzcx\\dzcx-srv\\target\\jar\\dzcx-srv-0.0.1-SNAPSHOT2.jar";
       FileInputStream f2 = new FileInputStream(fileOut2);
       byte[] b2 = new byte[average.intValue()];
       f2.read(b2);
       System.out.println("");
       System.out.print("b2---");
       for (int i = 0; i < b2.length; i ++) {
    	   //System.out.print(b2[i]);
    	   //System.out.print(",");
       }
       System.out.println(Arrays.equals(total, b1));
       System.out.println(total.length);
       System.out.println(b1.length);
       
       System.out.println(total[0]);
       System.out.println(b1[0]);
       System.out.println(total[total.length-1]);
       System.out.println(b1[b1.length-1]);
       System.out.println(total[total.length-2]);
       System.out.println(b1[b1.length-2]);
       
       System.out.println();
       System.out.println(Arrays.equals(total2, b2));
       System.out.println(total2.length);
       System.out.println(b2.length);
       
       System.out.println(total2[0]);
       System.out.println(b2[0]);
       System.out.println(total2[1]);
       System.out.println(b2[1]);
       System.out.println(total2[2]);
       System.out.println(b2[2]);
       System.out.println(total2[total2.length-1]);
       System.out.println(b2[b2.length-1]);
       System.out.println(total2[total2.length-2]);
       System.out.println(b2[b2.length-2]);
       for (int i = 0; i < 10000; i ++) {
    	   System.out.print(b2[b2.length - 1 - i]);
    	   System.out.print(",");
       }
       System.out.println();
       for (int i = 0; i < 10000; i ++) {
    	   System.out.print(total3[i] - 1 - i);
    	   System.out.print(",");
       }
       f.close();
       f1.close();
       f2.close();
       
       

   }
}
